# -*- coding =utf-8 -*-
# @Time :2022/11/8 21:53
# @Author : 皈小松 20031492
# @File :data_kmeans.py
# @Software: PyCharm
import pandas as pd
# 引入sklearn框架，导入K均值聚类算法
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

data_file = r'./data/supermarket_transform_data.xlsx'
result_file = r'./data/supermarket_type_data.xlsx'

data = pd.read_excel(data_file)  # 读取数据

k = 4  # 需要进行的聚类类别数
iteration = 500

# n-cluster	分类簇的数量
# max_iter	最大的迭代次数
k_model = KMeans(n_clusters=k, max_iter=iteration)
k_model.fit(data)  # 训练模型
r1 = pd.Series(k_model.labels_).value_counts()
r2 = pd.DataFrame(k_model.cluster_centers_)

r = pd.concat([r2, r1], axis=1)
r.columns = list(data.columns) + [u'聚类数量']
r3 = pd.Series(k_model.labels_, index=data.index)
r = pd.concat([data, r3], axis=1)
r.columns = list(data.columns) + [u'聚类类别']
r.to_excel(result_file)
k_model.cluster_centers_
k_model.labels_

# 避免中文乱码
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

for i in range(k):
    cls = data[r[u'聚类类别'] == i]
    cls.plot(linewidth=2, subplots=True, sharex=False, kind="kde")
    plt.suptitle('客户群=%d;聚类数量=%d' % (i, r1[i]))
    # plt.savefig('./客户群=%d;聚类数量=%d.jpg'% (i, r1[i]))  # 保存图片
plt.legend()
plt.show()
